﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KPIS.GERP.Models;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.Class;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    public class RepairController : Controller
    {
        //
        // GET: /Repair/

        public ActionResult Index()
        {
            var service = new RepairService.RepairServiceClient();
            var model = service.SelectRepair(new InventoryRepair()
            {
                RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus
            }, new[] { "Warehouse", "JobSite", "DealerRepair", "MasRepairStatus" }).ToList();

            return View(model);
        }

        public ActionResult Details(int id)
        {
            var service = new RepairService.RepairServiceClient();
            var model = service.SelectRepair(new InventoryRepair()
            {
                RepairId = id,
                RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus
            }, new[] { "Warehouse", "JobSite", "DealerRepair", "MasRepairStatus" }).FirstOrDefault();

            var ModelAsset = service.SelectAsset(new KPIS.GERP.Models.ICM.Asset()
            {
                AssetCode = model.AssetCode,
                RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus
            }, null).FirstOrDefault();
            ViewBag.AssetName = ModelAsset.AssetName;
            return View(model);
        }

        public ActionResult SearchAsset(int? id)
        {
            if (id != null)
            {
                ViewBag.AssetId = id;
                return View();
            }

            return View();
        }

        public ActionResult Create(int id)
        {
            ViewBag.AssetId = id;
            return View(new InventoryRepair());
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Create(InventoryRepair model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new RepairService.RepairServiceClient();                    
                    service.Insert(model, Class.GimsMembership.CurrentEmpId);

                    // อัพเดทสถานะครุภัณฑ์ว่า "ใช้งานได้" หรือ "ส่งซ่อม"
                    service.UpdateAssetStatus(model.RepairStatus, model.AssetCode, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Index");
                }
                return View(model);
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Edit(int id)
        {
            var service = new RepairService.RepairServiceClient();
            var item = service.SelectRepair(new InventoryRepair { RepairId = id }, new[] { "Warehouse", "JobSite", "DealerRepair" }).FirstOrDefault();
            
            if (item.AssetCode != null)
            {
                var asset = service.SelectAsset(new KPIS.GERP.Models.ICM.Asset()
                {
                    AssetCode = item.AssetCode,
                    RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus
                }, null).FirstOrDefault();

                ViewBag.AssetId = asset.AssetId;
            }


            if (item == null)
            {
                return HttpNotFound();
            }

            return View(item);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Edit(InventoryRepair model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new RepairService.RepairServiceClient();
                    service.Update(model, Class.GimsMembership.CurrentEmpId);

                    // อัพเดทสถานะครุภัณฑ์ว่า "ใช้งานได้" หรือ "ส่งซ่อม"
                    service.UpdateAssetStatus(model.RepairStatus, model.AssetCode, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Index");
                }
                return Edit(model.RepairId);
            }
            catch
            {
                return Edit(model.RepairId);
            }
        }

        public ActionResult Delete(int id)
        {
            try
            {
                var service = new RepairService.RepairServiceClient();
                service.Delete(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index");
            }
            catch
            {
                return Index();
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new RepairService.RepairServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.Delete(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        public void RepairReport(int RepairId)
        {
            var service = new RepairService.RepairServiceClient();
            var model = service.SelectRepair(new InventoryRepair()
            {
               RepairId = RepairId , RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus
            }, new[] { "Warehouse", "JobSite", "DealerRepair", "MasRepairStatus"}).ToList();
            var model1 = service.RepairName(RepairId);
            var model2 = service.AssetName(RepairId);

            MailMerge mailMerge = new MailMerge();
            Dictionary<string, string> fields = new Dictionary<string, string>();

            for (int i = 0; i < model.Count; i++)
            {
                fields.Add("ReceiveDate", model[i].RepairDate != null ? model[i].RepairDate.Value.ToShortDateString(): "");
                fields.Add("AssetName", model2[0]);
                if(model[i].WhId == null)
                {
                    fields.Add("JobSiteName", model[i].JobSite.Name);
                }
                else if(model[i].JobSiteId == null)
                {
                    fields.Add("JobSiteName", model[i].Warehouse.Name);
                }
                fields.Add("RepairDescr", model[i].RepairDescr);
                fields.Add("CreatedBy", model1[0]);
            }

            string strTemplatePath = Server.MapPath("~/Templates/ใบแจ้งซ่อม.docx");
            string strSaveAsPath = Server.MapPath("~/Temp/");
            string strSaveAsFileName = string.Format("ใบแจ้งซ่อม{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

            if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null, null, null))
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                Response.Flush();
                if (true)
                {
                    System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                }
                Response.End();
            }
        }
    }
}
 